import axios from 'axios';
import Vue from "vue";
import { Storage } from "@/utils/storage";
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  withCredentials: false, // 跨域请求时发送 cookies
  timeout: 5000 // request timeout
})

//请求拦截
service.interceptors.request.use(
  config => {
    // 接受自定义响应头
    config.headers['Access-Control-Expose-Headers'] = 'token'
    const methods = config.method.toLowerCase()
    if (methods === 'post' && !Array.isArray(config.data)) {
      const params = new URLSearchParams()
      Object.keys(config.data).forEach(key => {
          params.append(key.toString(), config.data[key].toString())
      })
      config.data = params
    } else if (methods === 'post' && !Array.isArray(config.data)) {
        config.headers['Content-Type'] = 'application/json'
    }
    const TOKEN = Storage.getItem('TOKEN')
    if (TOKEN != null) {
      config.headers.token = TOKEN
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
)

//响应拦截
service.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    Vue.prototype.$Message.error('error')
    return Promise.reject(error);
  }
)

export default service
